package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"smart-item-mgr/cache"
	"smart-item-mgr/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size
	var list []model.Shop
	redis_key := "list_" + strconv.Itoa(page)
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&list)
		JsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "数据展示成功",
		"data": list,
	})
	return
}

func CreateComment(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	sid, _ := strconv.Atoi(c.PostForm("sid"))
	content := c.PostForm("content")

	data := model.Comment{
		Uid:     uid,
		Sid:     sid,
		Content: content,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListComment(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size
	var list []model.Comment
	redis_key := "list_" + strconv.Itoa(page)
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&list)
		JsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "数据展示成功",
		"data": list,
	})
	return
}
